# -*- coding: utf-8 -*-
"""
    author: Ye
    date: 2021/01/25 11:14
"""
import json
from flask import Blueprint, jsonify, request
from flask.views import MethodView
from forms.api_schema import AuthorSchema, BookSchema
from models.api import Author, Book, db
from utils.permission import user_required

api_bp = Blueprint('api', __name__)


@api_bp.route('/author')
def author():
    authors = Author.query.all()
    author_schema = AuthorSchema(many=True)
    data = author_schema.dump(authors)
    return jsonify({'data': data})


class BookApiView(MethodView):

    decorators = [user_required]

    def get(self, book_id):
        print(book_id)
        if book_id:
            pass
        books = Book.query.join(Author).all()
        book_schema = BookSchema(many=True)
        # book_schema.author.books_count = 5
        data = book_schema.dump(books)
        return jsonify({'data': data})

    def post(self):
        print(request.form)
        book_schema = BookSchema()
        res = book_schema.load(request.form, session=db.session)

        db.session.add(res)
        db.session.commit()
        print(res)
        return jsonify(book_schema.dump(res))

    def put(self, book_id):
        print(book_id)
        print(request.data)
        return request.data

    def patch(self, book_id):
        print(book_id)
        print(request.data)
        return request.data

    def delete(self, book_id):
        print(book_id)
        print(request.data)
        return request.data


book_view = BookApiView.as_view('books')

api_bp.add_url_rule('/book', view_func=book_view, defaults={'book_id': None}, methods=['GET'])
api_bp.add_url_rule('/book', view_func=book_view, methods=['POST'])
api_bp.add_url_rule('/book/<int:book_id>', view_func=book_view, methods=['GET', 'PUT', 'DELETE'])
